import { MailOutlined, MobileOutlined } from '@ant-design/icons';
import { useRequest, useUnmount } from '@umijs/hooks';
import { Button, Form, Input, message } from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import React, { useEffect, useState } from 'react';
import cookie from "react-cookies";
import { addCookie, editCookie, getCookieValue } from '../../../utils/CookieUtil';
import { modifyFetch } from '../../../utils/Request';
import { url } from '../../../utils/url';
import { Link } from 'react-router-dom';
import { getRsaSecretString } from '../../../utils/encrypt';

//类型
interface CountType {
    count: string | number,
    counting: boolean,
    error: "" | "error" | "success" | "warning" | "validating" | undefined,
    message: string | undefined,

}

interface VerifyParams {
    step: number,
    validateToken: string,
    validateCode: string
}

export default function VerifyUser(props: { onNext: () => void; }) {

    const [data, setData] = useState<CountType>({ count: "", counting: false, error: "", message: undefined })
    // const [timer, settimer] = useState<any>(null)

    const [errorText, seterrorText] = useState<string>("")

    const [form] = Form.useForm();

    let timer: any = null

    //第一次进来的时候加载
    useEffect(() => {
        cookie.remove("token");
        cookie.save("token", "", { path: "/" });
        const count = getCookieValue("messageDept")
            ? getCookieValue("messageDept")
            : 0;

        // console.log(count)
        if (count !== undefined && count > 0) {
            setData({ error: "", message: "", count: count, counting: true })
            timer = setInterval(countDown, 1000)
        }

    }, [])


    // useInterval(() => { console.log(123123) }, 1000)

    //点击提交的时候
    const onFinish = (values: Store) => {

        const value: VerifyParams = {
            step: 1,
            validateToken: cookie.load(cookie.load("phoneDept") + "smsTokenDept"),
            validateCode: values.msgCode
        }
        submit.run(value)
        // props.onNext()
    };

    const submit = useRequest(verify, {
        manual: true,
        loadingDelay: 200
    })

    //请求验证
    async function verify(params: VerifyParams) {
        try {
            const json = await modifyFetch(url.MODIFY_PASSWORD, params)

            if (json.success) {
                props.onNext()
            } else {
                seterrorText(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    //发送短信
    const sendMessage = useRequest(send, {
        manual: true,
        loadingDelay: 200
    });

    //点击发送短信
    async function send() {

        form.validateFields(["phone"])
        const phoneNumber = form.getFieldValue("phone");
        // console.log(phoneNumber)
        if (!/^1[3456789]\d{9}$/.test(phoneNumber)) {
            setData({ ...data, error: "error", message: "手机号码格式错误" })
        } else {
            const value = { phone: phoneNumber }
            setData({ ...data, error: "", message: undefined })
            try {
                const json = await modifyFetch(url.SEND_MESSAGE_URL, { data: getRsaSecretString(JSON.stringify(value)) })
                if (json.success) {
                    // cookie.save(phoneNumber, json.smsToken, { path: "/", maxAge: 60 });
                    setData({ error: "", message: "", count: 60, counting: true })
                    addCookie("messageDept", "60", 60)
                    timer = setInterval(countDown, 1000)
                    cookie.save("phoneDept", phoneNumber, { path: '/', maxAge: 60 * 10 * 1000 });
                    cookie.save(phoneNumber + "smsTokenDept", json.validateSmsToken, { path: '/', maxAge: 60 * 10 * 1000 });
                    // setInterval(() => console.log(12312), 1000)
                } else {
                    message.destroy();
                    message.error(json.error);
                }

            } catch (error:any) {
                message.destroy();
                message.error(error.message)
            }
        }
    }


    //卸载的时候调用的方法
    useUnmount(() => {
        clearMyInterval(timer);
    })


    //去除定时任务
    function clearMyInterval(timer: any) {
        if (timer !== null) {
            clearInterval(timer)
        }

    }


    //设置倒计时的信息
    function countDown() {
        let oldCount = getCookieValue("messageDept");
        // console.log(oldCount)
        let count = 0;
        if (typeof oldCount !== "undefined")
            count = parseInt(oldCount);
        else
            count = 0;
        if (count <= 1) {
            clearMyInterval(timer);
            setData({ ...data, counting: false, count: 0 })
        } else {
            count--;
            setData({ counting: true, error: "", count: count, message: undefined })
        }
        editCookie("messageDept", count.toString(), count + 1);
    };



    // console.log(data)


    return (
        <Form form={form} onFinish={onFinish} >
            <Form.Item validateTrigger="onBlur" name="phone" rules={[{ required: true, message: '必须要输入手机号!' }, { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' }]}>
                <Input prefix={<MobileOutlined />} placeholder="手机号码" size="large" />
            </Form.Item>

            <Form.Item name="msgCode" rules={[{ required: true, message: '必须要短信验证码!' }]}>
                <Input prefix={<MailOutlined />} placeholder="短信验证码" size="large" addonAfter={
                    <Button
                        type="link"
                        onClick={() => sendMessage.run()}
                        loading={sendMessage.loading}
                        disabled={data.counting}
                        className={'verification'}
                    >
                        {data.counting ? `${data.count}秒后重发` : "获取验证码"}
                    </Button>
                } />
            </Form.Item>

            <Form.Item>
                <small style={{ color: "red" }}>{errorText}</small>
                <Button loading={submit.loading} type="primary" size="large" htmlType="submit">下一步</Button>

            </Form.Item>

            <Link to="/">返回登录</Link>
        </Form>
    )
}
